package com.example.war;

import javax.microedition.khronos.opengles.GL10;

import android.R.integer;
import android.content.Context;
import android.graphics.Bitmap;

public class Breathe {
    
    private Context mContext;
    private int mCurrentIndex = 0;
    private static final int NUM_FRAMES = 23;
    private Quad[] mFrames = new Quad[NUM_FRAMES];
    private static final int RES_IDS[] = {
        R.raw.breathe1, R.raw.breathe2, R.raw.breathe3, R.raw.breathe4,
        R.raw.breathe5, R.raw.breathe6, R.raw.breathe7, R.raw.breathe8,
        R.raw.breathe9, R.raw.breathe10, R.raw.breathe11, R.raw.breathe12,
        R.raw.breathe13, R.raw.breathe14, R.raw.breathe15, R.raw.breathe16,
        R.raw.breathe17, R.raw.breathe18, R.raw.breathe19, R.raw.breathe20,
        R.raw.breathe21, R.raw.breathe22, R.raw.breathe23
    };
    
    private float mAnimDuration;
    private float mFrameInterval;

    public Breathe(Context context, GL10 gl, float duration) {
        mContext = context;
        for (int i = 0; i < mFrames.length; i++) {
            mFrames[i] = new Quad(false);
            initQuad(gl, mFrames[i], RES_IDS[i]);
        }
        mAnimDuration = duration;
        mFrameInterval = duration * 1f / NUM_FRAMES;
    }

    private void initQuad(GL10 gl, Quad quad, int resId) {
        Bitmap bitmap = Utils.loadRawImage(mContext.getResources(), resId);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        quad.setSize(width, height);
        quad.setTexture(gl, bitmap, false);
        bitmap.recycle();
    }
    
    public void reset(long time) {
        mStartTime = time;
        mCurrentIndex = 0;
    }

    private long mStartTime;
    public void draw(GL10 gl) {
        long currentTime = System.currentTimeMillis();
        long elapseTime = currentTime - mStartTime;
        if (elapseTime > 0 && elapseTime < mAnimDuration) {
            mCurrentIndex = (int)(elapseTime / mFrameInterval);
            gl.glPushMatrix();
            gl.glRotatef(180, 0, 0, 1);
            mFrames[mCurrentIndex].draw(gl, 0, 0, 0, 0, true);
            gl.glPopMatrix();
        }
        
//        if (mLastDrawTime == 0 || currentTime - mLastDrawTime > (INTERVAL_TIME + mIntervalAdjust)) {
//            mCurrentIndex++;
//            if (mCurrentIndex >= NUM_FRAMES) {
//                mCurrentIndex = 1;
//                mIntervalAdjust = 0;
//            } else {
//                mIntervalAdjust = 0;
//            }
//            mLastDrawTime = System.currentTimeMillis();
//        }
//        gl.glPushMatrix();
//        gl.glRotatef(180, 0, 0, 1);
//        mFrames[mCurrentIndex].draw(gl, 0, 0, -125, 0, true);
//        gl.glPopMatrix();
    }
    
    public void clean(GL10 gl) {
        for (int i = 0; i < mFrames.length; i++) {
            mFrames[i].deleteTexture(gl);
        }
    }
}
